import {
  goodsConvert,
  recommendGoods,
  cilckRecord,
  login
} from '../../utils/api'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsId: '',
    source: '',
    sku: {},
    loading: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      goodsId: options.goodsId,
      source: options.source
    })
    const token = wx.getStorageSync('token')
    // 登录
    if (!token) {
      this.login(options.chiefUid)
    } else {
      this.goodsConvert()
      this.recommendGoods()
    }
  },

  onShareAppMessage: function () {
    return {
      title: this.data.sku.goodsName,
      path: 'pages/goodsDetail/goodsDetail?goodsId=' + this.data.goodsId + '&source=' + this.data.source + '&chiefUid=' + wx.getStorageSync('uid')

    }
  },
  /**
   * 商品转链
   */
  goodsConvert() {
    goodsConvert({
      goodsId: this.data.goodsId,
      source: this.data.source,
      subShareRate: wx.getStorageSync('rate')
    }).then(res => {
      this.setData({
        sku: res.data
      })
    })
  },
  recommendGoods() {
    recommendGoods({
      goodsId: this.data.goodsId,
      source: this.data.source
    }).then(res => {
      this.setData({
        skus: res.data,
        loading: false
      })
    })
  },
  login(chiefUid) {
    wx.login({
      timeout: 2000,
      success: res => {
        login({
          code: res.code,
          chiefUid: chiefUid
        }).then(res => {
          if (res.data) {
            wx.setStorageSync('token', res.data.token)
            wx.setStorageSync('formal', res.data.formal)
            wx.setStorageSync('rate', res.data.rate)
            wx.setStorageSync('uid', res.data.uid)
            this.goodsConvert()
            this.recommendGoods()
          }
        })
      }
    })
  },
  /**
   * 领券
   */
  skuBuy(e) {
    wx.navigateTo({
      url: '../goodsDetail/goodsDetail?goodsId=' + this.data.skus[e.currentTarget.dataset.index].goodsId + '&source=' + this.data.source,
    })
  },
  buy() {
    wx.navigateToMiniProgram({
      appId: this.data.sku.we_app_info.app_id,
      path: this.data.sku.we_app_info.page_path,
      success: res => {
        cilckRecord({
          clickType: 1002
        })
      }
    })
  }
})